package org.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 宋孟林
 * @description
 * @create: 2025/3/7 21:31
 */
@Configuration
public class RedisConfig {

    /**
     * @description redis序列化问题
     * @param lettuceConnectionFactory lettuce
     * @return redisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        //创建redisTemplate对象
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //设置连接工厂，指定redis的连接信息
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        //设置key序列化方式，使用string序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置value的序列化方式json，使用GenericJackson2JsonRedisSerializer替换默认序列化，将对象转换为json格式存储
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //设置hash数据类型的key为string类型的序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //设置hash数据类型的key为json类型的序列化器
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //初始化配置，使配置生效
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
